package io.gitee.zhangbinhub.acp.boot.tools

import org.springframework.http.server.reactive.ServerHttpRequest
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono
import reactor.util.context.Context

object ReactiveRequestContextHolder {
    @JvmField
    val CONTEXT_KEY: Class<ServerWebExchange> = ServerWebExchange::class.java

    @JvmStatic
    fun getRequest(): Mono<ServerHttpRequest> =
        Mono.deferContextual { data -> Mono.just(data) }.cast(Context::class.java)
            .filter { context -> hasRequestContext(context) }
            .flatMap { context -> getRequestContext(context) }

    private fun hasRequestContext(context: Context): Boolean =
        context.hasKey(CONTEXT_KEY)

    private fun getRequestContext(context: Context): Mono<ServerHttpRequest> =
        Mono.just((context.get(CONTEXT_KEY) as ServerWebExchange).request)
}